//
//  YWReplyDBManager.m
//  maintain
//
//  Created by Kyo on 16/9/1.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWReplyDBManager.h"
#import "YWDBTool.h"

#import "YWReply.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"

@implementation YWReplyDBManager
YWSingletonM(Manager)

- (FMDatabase*)fmdb{
    return [[YWDBTool shareDBTool] fmdb];
}
- (FMDatabaseQueue*)dbQeue{
    return [[YWDBTool shareDBTool] dbQeue];
}
#pragma mark - 评论表
- (BOOL)createReplyTable
{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'reply' (replyId integer,relationId integer,relationType smallint,replyType smallint,content text,atUserId integer,replyTime timestamp,replierId integer,isRead boolean DEFAULT 0,status smallint);";
    return [[self fmdb] executeUpdate:sql];
}

- (BOOL)updateReplyWithReplyArray:(NSArray*)replyArray
{
    if (replyArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockReplyArray = replyArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockReplyArray enumerateObjectsUsingBlock:^(YWReply* _Nonnull reply, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'reply' WHERE replyId=? ;";
            FMResultSet* set = [db executeQuery:sql, @(reply.replyId)];
            if ([set next]) {
                sql = @"UPDATE 'reply' SET relationId=?,relationType=?,replyType=?,content=?,atUserId=?,replyTime =?,replierId =?,status=? WHERE replyId=?;";
                executeResult = [db executeUpdate:sql, @(reply.relationId),@(reply.relationType),@(reply.type), reply.content,@(reply.atUser.uniqueId), @(reply.replyTime), @(reply.replier.uniqueId),@(reply.status), @(reply.replyId)];
            }
            else {
                sql = @"INSERT INTO 'reply' (replyId, relationId,relationType,replyType,content,atUserId,replyTime,replierId,status,isRead) VALUES (?, ?, ?, ?, ?, ?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, @(reply.replyId),@(reply.relationId),@(reply.relationType),@(reply.type), reply.content,@(reply.atUser.uniqueId), @(reply.replyTime), @(reply.replier.uniqueId),@(reply.status),@(reply.isRead)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateReplyIsReadWithType:(NSInteger)relationType;
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        if (relationType == YWReplyRelationTypeAll) {
            sql = @"UPDATE 'reply' SET isRead=?";
        }else{
            sql = @"UPDATE 'reply' SET isRead=? where relationType=?";
        }
        executeResult = [db executeUpdate:sql, @(1),@(relationType)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)deleteReplyWithReplyId:(NSInteger)replyId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"DELETE FROM 'reply' where replyId=? ";
        executeResult = [db executeUpdate:sql, @(replyId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSArray*)replysWithtRelationId:(NSInteger)relationId andRelationType:(NSInteger)relationType
{
    __block NSMutableArray* blockReplys = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'reply' SET isRead=? where relationType=?";
        [db executeUpdate:sql, @(1),@(relationType)];
        
        sql = @"SELECT * FROM 'reply' WHERE relationId=? AND relationType=? ORDER BY replyTime DESC;";
        FMResultSet* set = [db executeQuery:sql, @(relationId),@(relationType)];
        while ([set next]) {
            YWReply* reply = [self replyWithFMResultSet:set FMDatabase:db];
            [blockReplys addObject:reply];
        }
        [db closeOpenResultSets];
    }];
    return blockReplys.count ? blockReplys : nil;
}

- (NSArray*)noReadReplysWithRelationType:(NSInteger)relationType;
{
    __block YWLoginUser* currentUser = [YWLoginTool loginUser];
    __block NSMutableArray* blockReplys = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        //未读回复人不是自己的评论
        NSString* sql = nil;
        if (relationType == YWReplyRelationTypeAll) {
            sql = @"SELECT * FROM 'reply' WHERE isRead = 0 AND replierId!=? ORDER BY replyTime desc";
        }else{
            sql = @"SELECT * FROM 'reply' WHERE relationType=? AND isRead = 0 AND replierId!=? ORDER BY replyTime desc";
        }
        FMResultSet* set = [db executeQuery:sql, @(relationType),@(currentUser.uniqueId)];
        while ([set next]) {
            YWReply* reply = [self replyWithFMResultSet:set FMDatabase:db];
            [blockReplys addObject:reply];
        }
        [db closeOpenResultSets];
    }];
    return blockReplys;//.count ? blockReplys : nil;
}

- (NSInteger)noReadReplysCountWithRelationType:(NSInteger)relationType{
    __block NSInteger count = 0;
    __block YWLoginUser* currentUser = [YWLoginTool loginUser];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        if (relationType == YWReplyRelationTypeAll) {
            sql = @"SELECT COUNT(*) noReadReplysCount FROM 'reply' WHERE isRead = 0 AND replierId!=? ORDER BY replyTime desc";
        }else{
            sql = @"SELECT COUNT(*) noReadReplysCount FROM 'reply' WHERE relationType=? AND isRead = 0 AND replierId!=? ORDER BY replyTime desc";
        }
        FMResultSet* set = [db executeQuery:sql, @(relationType),@(currentUser.uniqueId)];
        if ([set next]) {
            count = [set longForColumn:@"noReadReplysCount"];
        }
        [db closeOpenResultSets];
    }];
    return count;
}

- (NSInteger)replysCountWithtRelationId:(NSInteger)relationId relationType:(NSInteger)relationType{
    __block NSInteger count = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT COUNT(*) noReadReplysCount FROM 'reply' WHERE relationId =? AND relationType =?";
        FMResultSet* set = [db executeQuery:sql, @(relationId),@(relationType)];
        if ([set next]) {
            count = [set longForColumn:@"noReadReplysCount"];
        }
        [db closeOpenResultSets];
    }];
    return count;
}

- (YWReply*)replyWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWReply *reply = [[YWReply alloc] init];
    reply.replyId = [set intForColumn:@"replyId"];
    reply.relationId = [set intForColumn:@"relationId"];
    reply.relationType = [set intForColumn:@"relationType"];
    reply.content = [set stringForColumn:@"content"];
    reply.replyTime = [set longLongIntForColumn:@"replyTime"];
    reply.isRead = [set boolForColumn:@"isRead"];
    reply.status = [set intForColumn:@"status"];
    
    NSInteger replierId = [set intForColumn:@"replierId"];
    NSString* creatorsql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
    FMResultSet* newSet = [db executeQuery:creatorsql, @(replierId)];
    if ([newSet next]) {
        reply.replier = [[YWDBTool shareDBTool] handlerWithSet:newSet];
    }
    NSInteger atUserId = [set intForColumn:@"atUserId"];
    NSString* atUserSql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
    newSet = [db executeQuery:atUserSql, @(atUserId)];
    if ([newSet next]) {
        reply.atUser = [[YWDBTool shareDBTool] handlerWithSet:newSet];
    }
    return reply;
}
@end
